package mygameclient;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class ClientUI extends JFrame {
    private JPanel buttonPanel;
    private JButton connectButton;
    private JButton playButton;
    private JButton disconnectButton;
    static PlayersPanel playersPanel;
    static GamePanel gamePanel;
    public JTextField nameField;

    public ClientUI() {

        playersPanel = new PlayersPanel();
        playersPanel.setVisible(true);
        playersPanel.setPreferredSize(new Dimension(350, 350));
        add(playersPanel, BorderLayout.EAST);

        gamePanel = new GamePanel();
        gamePanel.setVisible(true);
        add(gamePanel, BorderLayout.WEST);

        buttonPanel = new JPanel();
        buttonPanel.setPreferredSize(new Dimension(200, 50));
        add(buttonPanel, BorderLayout.SOUTH);
        buttonPanel.setVisible(true);

        connectButton = new JButton("Connect");
        playButton = new JButton("Play");
        disconnectButton = new JButton("Disconnect");
        nameField = new JTextField();
        nameField.setPreferredSize(new Dimension(300, 27));

        buttonPanel.add(connectButton);
        buttonPanel.add(playButton);
        buttonPanel.add(disconnectButton);
        buttonPanel.add(nameField);

        disconnectButton.setEnabled(false);

        pack();

        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userName = nameField.getText();
                if (userName.isEmpty()) {
                    MessageBox.ok("Enter your name");
                } else {
                    ClientCommands.connectGame(userName);
                    nameField.setEditable(false);
                    connectButton.setEnabled(false);
                    disconnectButton.setEnabled(true);
                }
            }
        });

        playButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int playerCode = playersPanel.getPlayer().getpHashCode();
                ClientCommands.gameRequest(playerCode);
                System.out.println("" + playerCode);
            }
        });

        disconnectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ClientCommands.closeConnection();
                nameField.setEditable(true);
                connectButton.setEnabled(true);
                disconnectButton.setEnabled(false);
                gamePanel.erasePanel();
            }
        });
    }
}
